package com.starchen.optimalselection.admin.controller;

import com.starchen.optimalselection.admin.model.form.LoginForm;
import com.starchen.optimalselection.admin.model.vo.LoginVo;
import com.starchen.optimalselection.admin.service.AdminUserService;
import com.starchen.optimalselection.common.utils.IpUtil;
import com.starchen.optimalselection.common.utils.Result;
import com.starchen.optimalselection.config.security.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/admin/index")
public class IndexController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminUserService sysUserService;

    @ApiOperation(value = "登录以后返回token")
    @PostMapping("/login")
    public Result login(HttpServletRequest request,@Valid @RequestBody LoginForm loginVo) {
        String ipAddress = IpUtil.getIpAddress(request);
        LoginVo login = sysUserService.login(loginVo,ipAddress);

        return Result.success(login);
    }

    @ApiOperation(value = "登录后获取菜单和用户信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {

        String authToken = request.getHeader(this.tokenHeader);
        String username = jwtTokenUtil.getUserNameFromToken(authToken);

        //根据用户名称获取用户信息（基本信息 和 菜单权限 和 按钮权限数据）
        Map<String,Object> map = sysUserService.getUserInfo(username);
        return Result.success(map);
    }

    @ApiOperation(value = "登出功能")
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String authToken = request.getHeader(this.tokenHeader);
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        sysUserService.logout(username);
        return Result.success();
    }

}
